package com.ks.pc.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ks.dto.BrandDto;
import com.ks.dto.KVItemDto;
import com.ks.dto.OtherDto;
import com.ks.dto.PaginationDto;
import com.ks.dto.Product2Dto;
import com.ks.dto.UserInfoDto;
import com.ks.pc.dao.DaoSupport;
import com.ks.pc.service.SysOtherService;
import com.ks.utils.DeleteFileHandle;

import net.chinahrd.utils.CollectionKit;
import net.chinahrd.utils.WebUtils;

@Service("sysOtherService")
public class SysOtherServiceImpl implements SysOtherService {

	public static final Logger logger = Logger.getLogger(SysProductServiceImpl.class);

	@Autowired
	private DaoSupport daoSupport;

	public boolean updateAbout(OtherDto dto) {
		try {
			daoSupport.update("OtherMapper.updateOtherById", dto);
			return true;
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return false;
	}

	public OtherDto findOtherById(int id) {
		try {
			return daoSupport.findForObject("OtherMapper.findOtherById", id);
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return null;
	}

	@Override
	public boolean delFileImgs() {
		String path = WebUtils.getAbsolutePath();
		boolean flag = false;
		try {
			List<KVItemDto> kvs = daoSupport.findForList("OtherMapper.findImgNotRel", null);
			List<Object> list = new ArrayList<Object>();
			if (0 == kvs.size()) {
				flag = true;
			}
			for (KVItemDto kv : kvs) {
				boolean delFileFlag = false;
				delFileFlag = DeleteFileHandle.delectFile(path + kv.getV());
				if (delFileFlag) {
					list.add(kv.getK());
				}
			}
			if (0 != list.size()) {
				daoSupport.batchDelete("OtherMapper.delFileImgsById", list);
				flag = true;
			}
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return flag;
	}

	@Override
	public PaginationDto<UserInfoDto> findOnlineOpt(PaginationDto<UserInfoDto> pageDto, Map<String, Object> param) {
		List<UserInfoDto> dtos = null;
		try {
			Integer count = daoSupport.findForObject("OtherMapper.findOnlineOptCount", param);
			dtos = daoSupport.findForList("OtherMapper.findOnlineOpt", param);
			pageDto.setRecords(count);
			pageDto.setRows(dtos);
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return pageDto;
	}

	@Override
	public void export(HttpServletRequest request, HttpServletResponse response) {
		List<UserInfoDto> dtos = null;
		try {
			RowBounds rowBounds = new RowBounds(9999, 9999);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("searchTxt", null);
			param.put("rowBounds", rowBounds);
			dtos = daoSupport.findForList("OtherMapper.findOnlineOpt", param);
			if (null != dtos) {
				exportExcel("预约客户", dtos, "customer.xls", request, response);
			}
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}

	}

	@SuppressWarnings("deprecation")
	private void exportExcel(String sheetName, List<UserInfoDto> list, String fileName, HttpServletRequest request,
			HttpServletResponse response) {
		// 声明一个工作薄
		HSSFWorkbook wb = new HSSFWorkbook();
		// 声明一个单子并命名
		HSSFSheet sheet = wb.createSheet(sheetName);
		// 给单子名称一个长度
		sheet.setDefaultColumnWidth((short) 15);
		// 生成一个样式
		HSSFCellStyle style = wb.createCellStyle();
		// 创建第一行（也可以称为表头）
		HSSFRow row = sheet.createRow(0);
		// 样式字体居中
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 给表头第一行一次创建单元格
		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("名称");
		// cell.setCellStyle(style);
		cell = row.createCell((short) 1);
		cell.setCellValue("手机");
		// cell.setCellStyle(style);
		cell = row.createCell((short) 2);
		cell.setCellValue("身份证号");
		// cell.setCellStyle(style);
		cell = row.createCell((short) 3);
		cell.setCellValue("是否办理过分期");
		// cell.setCellStyle(style);
		cell = row.createCell((short) 4);
		cell.setCellValue("描述");
		cell.setCellStyle(style);

		// 向单元格里填充数据
		for (short i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 1);
			row.createCell(0).setCellValue(list.get(i).getUserName());
			row.createCell(1).setCellValue(list.get(i).getUserPhoneNum());
			row.createCell(2).setCellValue(list.get(i).getUserIDCard());
			row.createCell(3).setCellValue(list.get(i).getUserStages());
			row.createCell(4).setCellValue(list.get(i).getUserNote());
		}
		String path = WebUtils.getServletContext().getRealPath(fileName);
		write(wb, path, response);
		download(path, response);
	}

	/**
	 * 从wb缓存里生成文件，并保存在项目的相对路径下
	 * 
	 * @param wb
	 * @param path
	 *            项目的相对路径
	 * @param response
	 */
	private void write(HSSFWorkbook wb, String path, HttpServletResponse response) {
		try {
			// 本地下载
			// String path = "D:\\customer.xls";
			// String fileName = new String(path.getBytes("GB2312"),
			// "ISO_8859_1");
			// response.reset();
			// response.setContentType("application/octet-stream");
			// response.setContentType("application/vnd.ms-excel");
			// response.setContentType("application/x-xls");
			// response.setHeader("Content-disposition", "inline; attachment;
			// filename=" + fileName + "");
			FileOutputStream out = new FileOutputStream(path);
			wb.write(out);
			// JOptionPane.showMessageDialog(null, 导出成功!);
		} catch (FileNotFoundException e) {
			// JOptionPane.showMessageDialog(null, 导出失败!);
			e.printStackTrace();
		} catch (IOException e) {
			// JOptionPane.showMessageDialog(null, 导出失败!);
			e.printStackTrace();
		}
	}

	/**
	 * 必须先调write()， 从生成好的文件，让浏览器可以弹“另存为”窗口
	 * 
	 * @param path
	 * @param response
	 */
	private void download(String path, HttpServletResponse response) {
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/vnd.ms-excel;charset=gb2312");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public boolean deleteOnlineOptByIds(String idsArr) {
		String[] split = StringUtils.split(idsArr);
		List<String> ids = Arrays.asList(split);
		try {
			daoSupport.delete("OtherMapper.deleteOnlineOptByIds", ids);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean updateShowIndex(BrandDto[] brands, Product2Dto[] products) {
		boolean flag = false;
		try {
			if (brands.length > 0) {
				List<BrandDto> list = filterBrandDto(brands);
				if (list.size() > 0) {
					daoSupport.update("OtherMapper.updateBatchBrandShowIndex", list);
					flag = true;
				}
			}
			if (products.length > 0) {
				List<Product2Dto> list = filterProductDto(products);
				if (list.size() > 0) {
					daoSupport.update("OtherMapper.updateBatchProductShowIndex", list);
					flag = true;
				}
			}
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 过滤，没有showIndex变的对象
	 * 
	 * @param brands
	 * @param count
	 */
	private List<BrandDto> filterBrandDto(BrandDto[] brands) {
		List<BrandDto> updataDto = CollectionKit.newList();
		int count = brands.length;
		int newShowIndex = count - 1;
		int index = 0;
		while (count > 0) {
			int oldShowIndex = brands[index].getShowIndex();
			// 旧的顺序是由数组提供，第一个元素为最大值倒序。这里是否和旧的顺序一样
			if (oldShowIndex != newShowIndex) {
				BrandDto dto = new BrandDto();
				dto.setId(brands[index].getId());
				dto.setShowIndex(newShowIndex);
				updataDto.add(dto);
			}
			count--;
			newShowIndex--;
			index++;
		}
		return updataDto;
	}

	/**
	 * 过滤，没有showIndex变的对象
	 * 
	 * @param product
	 * @param count
	 */
	private List<Product2Dto> filterProductDto(Product2Dto[] product) {
		List<Product2Dto> updataDto = CollectionKit.newList();
		int count = product.length;
		int newShowIndex = count - 1;
		int index = 0;
		while (count > 0) {
			int oldShowIndex = product[index].getShowIndex();
			// 旧的顺序是由数组提供，第一个元素为最大值倒序。这里是否和旧的顺序一样
			if (oldShowIndex != newShowIndex) {
				Product2Dto dto = new Product2Dto();
				dto.setId(product[index].getId());
				dto.setShowIndex(newShowIndex);
				updataDto.add(dto);
			}
			count--;
			newShowIndex--;
			index++;
		}
		return updataDto;
	}

}
